﻿using Microsoft.AspNetCore.Mvc.Filters;
using SqlSugar;
using XiheNet;

namespace Com.Core.Module.Filters;

[AttributeUsage(AttributeTargets.Method)]
public class TransactionalFilter : System.Attribute, IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(
        ActionExecutingContext context,
        ActionExecutionDelegate next
    )
    {
        var db = context.HttpContext.RequestServices.GetRequiredService<ISqlSugarClient>();

        if (db.Ado.Transaction != null)
        {
            await next();
            return;
        }

        try
        {
            db.Ado.BeginTran();
            var result = await next();

            if (result.Exception == null)
            {
                db.Ado.CommitTran();
            }
            else
            {
                db.Ado.RollbackTran();
            }
        }
        catch (XException)
        {
            db.Ado.RollbackTran();
            throw;
        }
        catch (Exception)
        {
            db.Ado.RollbackTran();
            throw;
        }
    }
}

